/*
 * Copyright (C) 2014 luke.
 * 
 * This file is part of Silvie.
 * 
 * Silvie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Silvie is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Silvie.  If not, see <http://www.gnu.org/licenses/>.
 */

package silvie.resources.chrmodel.chunks;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import utils.DataReader;

/**
 * Abstract CHR "chunk". CHR chunks begin with a 4-byte int ID, then another int
 * for the size of the data that follows. The data itself contains the chunk's
 * information, and possibly "child" chunks.
 * 
 * @author luke
 */
public abstract class AbstractChunk {
	private static final String CHUNK_CLASS_PREFIX = "silvie.resources.chrmodel.chunks.Chunk0x";
	protected int id;
	protected byte[] data;
	protected List<AbstractChunk> children;
	private int bytesRead;

	/**
	 * AbstractChunk constructor.
	 * 
	 * @param id the chunk's ID.
	 * @param data the chunk's data.
	 */
	public AbstractChunk(int id, byte[] data) {
		this.id = id;
		this.data = data;
		this.children = new ArrayList<AbstractChunk>();
		this.bytesRead = 0;
	}

	/**
	 * Recursive method for reading this chunk's information and descend in
	 * child chunks.
	 * 
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws ClassNotFoundException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public void readContents() throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		this.bytesRead += decode();
		while (haveMoreChunks()) {
			int chunkId = DataReader.readInt(this.data, this.bytesRead);
			this.bytesRead += DataReader.INT_SIZE;
			int chunkSize = DataReader.readInt(this.data, this.bytesRead);
			this.bytesRead += DataReader.INT_SIZE;
			byte[] chunkData = new byte[chunkSize];
			System.arraycopy(this.data, this.bytesRead, chunkData, 0, chunkSize);
			this.children.add(newChunk(chunkId, chunkData));
			this.bytesRead += chunkSize;
		}
		for (AbstractChunk chunk : this.children) {
			chunk.readContents();
		}
	}

	/**
	 * Reads this chunk's information.
	 * 
	 * @return the offset in {@code data} at which the information ends and
	 *         possible child chunks begin. This value is {@code data.length} if
	 *         there is no child chunk in the data.
	 */
	protected abstract int decode();

	/**
	 * Asserts whether this chunk contains child chunks. {@code decode()} must
	 * have been called before.
	 * 
	 * @return true if this chunk has child chunks, false otherwise.
	 */
	private boolean haveMoreChunks() {
		return this.bytesRead < this.data.length;
	}

	/**
	 * Instantiates the appropriate AbstractChunk specialization based on
	 * {@code chunkId}. It can be any chunk in the
	 * {@code silvie.resources.chrmodel.chunks} package.
	 * 
	 * @param chunkId the chunk's ID.
	 * @param chunkData the chunk's data.
	 * @return the appropriate AbstractChunk specialization corresponding to
	 *         {@code chunkId}.
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws ClassNotFoundException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	private static AbstractChunk newChunk(int chunkId, byte[] chunkData) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		String chunkClassName = CHUNK_CLASS_PREFIX + Integer.toHexString(chunkId);
		Constructor<?> constructor = Class.forName(chunkClassName).getDeclaredConstructor(int.class, Class.forName("[B"));
		constructor.setAccessible(true);
		return (AbstractChunk) constructor.newInstance(chunkId, chunkData);
	}

	/**
	 * Recursive method for finding all "descendant" chunks with ID
	 * {@code chunkId} from this chunk down.
	 * 
	 * @param chunkId the ID of the chunks to return.
	 * @return a list containing all chunks whose ID is {@code chunkId}.
	 */
	public List<AbstractChunk> getChunksById(int chunkId) {
		List<AbstractChunk> results = new ArrayList<AbstractChunk>();
		if (this.id == chunkId) {
			results.add(this);
		}
		for (AbstractChunk child : this.children) {
			results.addAll(child.getChunksById(chunkId));
		}
		return results;
	}
}
